package com.laicunba.event.listener;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.event.SellOutEvent;
import com.laicunba.pojo.FinancingTargetDO;
import com.laicunba.pojo.FinancingTargetPositionDO;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.service.FinancingTargetPositionService;
import com.laicunba.service.FinancingTargetService;
import com.laicunba.service.RegistryService;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.StringUtil;

/**
 * 自动补货监听
 * 
 * @author why
 *
 */
@Component
public class AutoReplenishmentListener implements ApplicationListener<SellOutEvent> {
	private static final Logger LOG = Logger.getLogger(AutoReplenishmentListener.class);
	@Autowired
	private FinancingTargetPositionService financingTargetPositionService;
	@Autowired
	private FinancingTargetService financingTargetService;
	@Autowired
	private RegistryService registryService;

	@Override
	public void onApplicationEvent(SellOutEvent event) {
		try {

			
			
			// 1、将剩下的尾巴库存处理掉<br/>
			FinancingTargetDO targetDO = financingTargetService.get(FinancingTargetDO.class, event.getSource().toString());
			
			//防止重复执行
			if(StringUtil.isNotEmpty(CacheUtil.getAttribute("sys.auto.replenishement."+targetDO.getId()))){
				return ;
			}
			CacheUtil.setAttribute("sys.auto.replenishement."+targetDO.getId(), "1", 36000);
			
			LOG.info(String.format("标的[%s]自动虚拟满标[%s]->[%s]", targetDO.getId(), targetDO.getFinishAmount(), targetDO.getCollectAmount()));
			targetDO.setFinishAmount(targetDO.getCollectAmount());
			financingTargetService.updateSkipCheckOwner(targetDO);

			// 3、上架同期限预备产品<br/>
			/**
			 **/ 
			 
//			List<FinancingTargetPositionDO> list = financingTargetPositionService.findPreparedList(targetDO.getPeriod());
//			if (list == null || list.isEmpty()) {
//				// 4、如果没有同期限预备产品,短信通知清算
//			} else { 
//				String positionTargetId = null;
//				for (FinancingTargetPositionDO position : list) {
//					if (positionTargetId == null) {
//						positionTargetId = position.getFinancingTargetId();
//					}
//					if (!position.getFinancingTargetId().equalsIgnoreCase(positionTargetId)) {
//						continue;
//					}
//					position.setBeginTime(new Date());
//					financingTargetPositionService.updateSkipCheckOwner(position);
//				}
//			}
			
			
			List<FinancingTargetPositionDO>  list = financingTargetPositionService.findByTargetId(targetDO.getId());

			
			// 找到自动上标计划的产品
			List<RegistryDO> registryDOList= registryService.like("sys.publish.plan.", targetDO.getId());
			if(registryDOList==null||registryDOList.isEmpty()){
				//4、如果没有同期限预备产品,短信通知清算
			}else{
				RegistryDO way =	registryDOList.get(0);
				JSONArray targetArray= (JSONArray) new JSONParser().parse(way.getVal()); 
				if(targetArray.size()>0){
					for(int i=0;i<targetArray.size();i++){
						if(targetDO.getId().equals(((JSONObject)targetArray.get(i)).get("id"))){
							targetArray.remove(i);
							break;
						}
					}
				} 
				if(list!=null&&targetArray.size()>0){
					//将第一个产品放到开售列表中
					String newSaleTargetId=((JSONObject)targetArray.get(0)).get("id").toString();
					for(FinancingTargetPositionDO oldPositionDO:list){
						FinancingTargetPositionDO newPositionDO = new FinancingTargetPositionDO();
						newPositionDO.setPosition(oldPositionDO.getPosition());
						newPositionDO.setFinancingTargetId(newSaleTargetId);
						newPositionDO.setBeginTime(new Date());
						newPositionDO.setEmdTime(new Date());
						newPositionDO.getEmdTime().setYear(newPositionDO.getEmdTime().getYear()+1); 
						financingTargetPositionService.create(newPositionDO);
					}
				}
				registryService.update(way.getId(), targetArray.toJSONString());
				
			}
			
			// 2、将其放入已售罄列表<br/>
			if (list != null) {
				for (FinancingTargetPositionDO position : list) { 
					financingTargetPositionService.delete(position.getId());
				}
			}
			FinancingTargetPositionDO position = new FinancingTargetPositionDO();
			Date endTime = new Date();
			endTime.setYear(endTime.getYear() + 1);
			position.setBeginTime(new Date());
			position.setEmdTime(endTime);
			position.setFinancingTargetId(targetDO.getId());
			position.setPosition("APP_SELLOUT_LIST");
			financingTargetPositionService.create(position);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
